//
//  RHUserGroupDetailVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/11/14.
//

#import "RHUserGroupDetailVC.h"
#import <MGSwipeButton.h>
#import "RHUserListCell.h"
#import "RHUserModel.h"
#import "RHUserDetailVC.h"
#import "RHGroupAddUserVC.h"
#import "RHSearchView.h"
#import "RHUserGroupModel.h"

@interface RHUserGroupDetailVC ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *userArr;

//由于上拉加载及分类不方便在下级实现,所以抽到上层处理
@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@property (nonatomic, strong) RHSearchView *searchView;

@end

@implementation RHUserGroupDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"用户列表".rh_localized;
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    self.numOfPage = 10;
    [self getUserListOfGroup];
    [self setupUI];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)getUserListOfGroup
{
    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@/%ld",H_userGroupListDetail,self.groupModel.groupId];
    NSDictionary *para = @{@"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"email":ValidNullData(self.searchView.searchTextField.text)
                           
    };
    [RHUserModel startGetWithCompletionAPIKey:url argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSInteger total = [request.responseObject[@"total"] integerValue];
            self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
        
            self.userArr = [resultModel.data mutableCopy];
            //下拉刷新
            if(self.requestType == RequestTypeRefresh){
                self.userArr = [resultModel.data mutableCopy];
                [self.tableView endHeaderRefresh];
            }else{//上拉加载
                [self.tableView endFooterRefresh];
                [self.userArr addObjectsFromArray:resultModel.data];
                
            }
            if(self.currentPage >= self.totalPage){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
            [self.tableView reloadData];
        }
    
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        [self.tableView endFooterRefresh];
    }];
    
}

#pragma mark ---- 分组删除用户 -----
-(void)deleteUserFromGroup:(NSInteger)index
{
    RHUserModel *userModel = [self.userArr safeObjectAtIndex:index];
    NSString *url = [NSString stringWithFormat:@"user/groups/user/%ld",self.groupModel.groupId];
    [QMUITips showLoadingInView:kApplication.keyWindow];
    [BaseModel startDeleteWithCompletionAPIKey:url argument:@{@"ids":@(userModel.userId)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [self.userArr removeObjectAtIndex:index];
            [self.tableView reloadData];
            [QMUITips showSucceed:@"成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self getUserListOfGroup];
            });
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

- (void)setupUI{
    kWeakSelf;
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    [self.view addSubview:_searchView];
    _searchView.delegate = self;
    _searchView.searchTextField.placeholder = @"请输入用户邮箱".rh_localized;
   
    
    UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,40, 64)];
    [addButton setImage:[UIImage imageNamed:@"create_user"] forState:UIControlStateNormal];
    [addButton setBackgroundColor:UIColor.clearColor];
    [addButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [addButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [addButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    //[addButton addTarget:self action:@selector(didClickAdd) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    self.navigationItem.rightBarButtonItem = rightBarBtn;

    [[addButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        RHGroupAddUserVC *vc = [[RHGroupAddUserVC alloc] init];
        vc.groupModel = self.groupModel;
        kWeakSelf;
        vc.addFinishBlock = ^{
            [weakSelf getUserListOfGroup];
        };
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getUserListOfGroup) name:SwitchRegionSuccessNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getUserListOfGroup) name:UserModifyRemarkName object:nil];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHUserListCell class] forCellReuseIdentifier:@"RHUserListCell"];
    [self.view addSubview:_tableView];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        //_resultTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
        //_resultTableView.sectionHeaderTopPadding = 0;
    }
    
    
   
    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView endFooterResetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        [weakSelf getUserListOfGroup];
    }];
    
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getUserListOfGroup];
    }];
    
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
        make.top.equalTo(weakSelf.searchView.mas_bottom);
    }];
    
    self.tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"No data" detailStr:@""];
    
    
}



#pragma mark -------  tableView delegate -------

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.userArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHUserModel *userModel = self.userArr[indexPath.row];
    RHUserListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHUserListCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.usermodel = userModel;
    kWeakSelf;
    MGSwipeButton *oneBtn = [MGSwipeButton buttonWithTitle:@"   " icon:[UIImage imageNamed:@"plant_delete"] backgroundColor:CFTabViewBgColor padding:15 callback:^BOOL(MGSwipeTableCell * _Nonnull cell) {
        QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleCancel handler:NULL];
        QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
            [weakSelf deleteUserFromGroup:indexPath.row];
        }];
        QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"删除此用户?".rh_localized message:nil preferredStyle:QMUIAlertControllerStyleAlert];
        [alertController addAction:action1];
        [alertController addAction:action2];
        [alertController showWithAnimated:YES];
        
        return YES;
    }];
    //终端用户才有删除功能
    cell.rightButtons = @[oneBtn];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RHUserModel *userModel = self.userArr[indexPath.row];
    RHUserDetailVC *detailVC = [[RHUserDetailVC alloc]init];
    detailVC.usermodel = userModel;
    [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark ------- textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    [self getUserListOfGroup];
    [self.searchView resignFirstResponder];
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getUserListOfGroup];
        [self.searchView resignFirstResponder];
    });
    return YES;
}

#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end
